<template>
  <div class="">
    <!-- <el-page-header @back="back">
      <template slot="title">
        <span class="back">返回</span>
      </template>
      <template slot="content">
        <span class="back pr-4">指标目标</span>
      </template>
    </el-page-header> -->
    <div>
      <avue-form
        ref="form"
        v-model="form"
        :option="option"
        :defaults.sync="defaults"
        :class="{ avue: !!parentId && isDetail }"
        @submit="submit"
      >
        <template slot="parent">
          <el-row>
            <el-col :span="24" :class="{ 'parent-title': !!parentId }">
              <el-form-item label="上级目标">
                <el-input :value="parentData.name" disabled></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row style="margin-top: 10px">
            <el-col :span="12" :class="{ target: !!parentId }">
              <el-form-item label="目标值">
                <el-input :value="parentData.targetValue" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" :class="{ date: !!parentId }">
              <el-form-item label="时间范围">
                <el-date-picker
                  type="daterange"
                  :value="parentData.datePeriod"
                  align="right"
                  unlink-panels
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  disabled
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
        </template>
        <template slot="menuForm" slot-scope="{ size }">
          <el-button :size="size" @click="back">取消</el-button>
          <el-button type="primary" :size="size" @click="$refs.form.submit()">提交</el-button>
          <!-- <el-button plain :size="size" @click="$refs.form.resetForm()">暂存</el-button> -->
        </template>
        <template slot="ruleJson">
          <RuleForm ref="ruleform" :data="form.ruleJson" :is-detail="isDetail"></RuleForm>
        </template>
        <template slot="valueFormat">
          <ValueFormater v-model="form.valueFormat" :disabled="isDetail"></ValueFormater>
        </template>
        <template slot="datePeriod">
          <el-date-picker
            v-if="form.dateType !== '季度'"
            :key="form.dateType"
            v-model="form.datePeriod"
            :type="dateTypeMap[form.dateType]"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :disabled="!form.dateType"
            :append-to-body="false"
          >
          </el-date-picker>
          <el-select v-else v-model="form.datePeriod" placeholder="请选择季度">
            <el-option label="Q1" value="Q1"> </el-option>
            <el-option label="Q2" value="Q2"> </el-option>
            <el-option label="Q3" value="Q3"> </el-option>
            <el-option label="Q4" value="Q4"> </el-option>
          </el-select>
        </template>
        <!-- <template slot="dimension">
          <el-select v-model="form.dimension" placeholder="请选择维度" @change="onDimensionChange">
            <el-option v-for="item in xList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
          </el-select>
        </template> -->
        <!-- <template slot="matrix">
          <el-select v-model="form.matrix" placeholder="请选择指标" @change="onMatrixChange">
            <el-option v-for="item in yList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
          </el-select>
        </template> -->
      </avue-form>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { save, getDetail, update, getDBLastData } from '@/api/target/target'
import RuleForm from './components/ruleForm.vue'
import moment from 'moment'
import ValueFormater from '@/components/valueFormatter'
export default {
  components: {
    RuleForm,
    ValueFormater,
  },
  props: {
    parentId: {
      type: [Number, String],
      default: '',
    },
    id: {
      type: [Number, String],
      default: '',
    },
    isDetail: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    var validateNum = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入目标值'))
      } else if (value / 1 <= 0) {
        callback(new Error('目标值需大于0'))
      } else if (value / 1 < this.form.initValue / 1) {
        callback(new Error('目标值不得小于初始值'))
      } else {
        callback()
      }
    }
    var validateNum1 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入当前值'))
      } else if (value / 1 < this.form.initValue / 1) {
        callback(new Error('当前值不得小于初始值'))
      } else {
        callback()
      }
    }
    return {
      loading: true,
      form: {},
      defaults: {},
      listObj: [],
      xList: [],
      yList: [],
      option: {
        detail: false,
        submitBtn: false,
        emptyBtn: false,
        menuPosition: 'right',
        menuLeft: false,
        labelSuffix: ' ',
        group: [
          {
            label: '目标基础信息',
            arrow: true,
            prop: 'mbdy',
            column: [
              {
                label: '目标名称',
                prop: 'name',
                span: 12,
                rules: [{ required: true, message: '请输入目标名称' }],
              },
              {
                label: '日期类型',
                prop: 'dateType',
                type: 'select',
                span: 12,
                rules: [{ required: true, message: '请选择日期类型' }],
                dicData: [
                  { label: '年度', value: '年度' },
                  { label: '季度', value: '季度' },
                  { label: '月', value: '月' },
                  { label: '周', value: '周' },
                  { label: '日', value: '日' },
                  { label: '自定义', value: '自定义' },
                ],
                control: (val) => {
                  this.form.datePeriod = ''
                  // this.$set(this.defaults.datePeriod,'type',this.dateTypeMap[this.form.dateType])
                },
              },
              {
                label: '日期范围',
                prop: 'datePeriod',
                span: 12,
                rules: [{ required: true, message: '请选择目标期间' }],
                dicData: [
                  { label: 'Q1', value: 'Q1' },
                  { label: 'Q2', value: 'Q2' },
                  { label: 'Q3', value: 'Q3' },
                  { label: 'Q4', value: 'Q4' },
                ],
                control: (val) => {
                  if (this.form.dateType === '年度') {
                    this.form['beginTargetPeriod'] = moment(val).startOf('year').format('YYYY-MM-DD 00:00:00')
                    this.form['endTargetPeriod'] = moment(val).endOf('year').format('YYYY-MM-DD 23:59:59')
                  } else if (this.form.dateType === '季度') {
                    const map = {
                      Q1: moment().format('YYYY') + '-01-01',
                      Q2: moment().format('YYYY') + '-04-01',
                      Q3: moment().format('YYYY') + '-07-01',
                      Q4: moment().format('YYYY') + '-10-01',
                    }
                    this.form['beginTargetPeriod'] = moment(map[val]).startOf('quarter').format('YYYY-MM-DD 00:00:00')
                    this.form['endTargetPeriod'] = moment(map[val]).endOf('quarter').format('YYYY-MM-DD 23:59:59')
                  } else if (this.form.dateType === '月') {
                    this.form['beginTargetPeriod'] = moment(val).startOf('month').format('YYYY-MM-DD 00:00:00')
                    this.form['endTargetPeriod'] = moment(val).endOf('month').format('YYYY-MM-DD 23:59:59')
                  } else if (this.form.dateType === '周') {
                    this.form['beginTargetPeriod'] = moment(val).startOf('week').format('YYYY-MM-DD 00:00:00')
                    this.form['endTargetPeriod'] = moment(val).endOf('week').format('YYYY-MM-DD 23:59:59')
                  } else if (this.form.dateType === '日') {
                    this.form['beginTargetPeriod'] = moment(val).format('YYYY-MM-DD 00:00:00')
                    this.form['endTargetPeriod'] = moment(val).format('YYYY-MM-DD 23:59:59')
                  } else if (this.form.dateType === '自定义') {
                    this.form['beginTargetPeriod'] = moment(val[0]).format('YYYY-MM-DD 00:00:00')
                    this.form['endTargetPeriod'] = moment(val[1]).format('YYYY-MM-DD 23:59:59')
                  }
                },
              },
              {
                label: '责任部门',
                prop: 'responsibleDeptId',
                type: 'tree',
                props: {
                  label: 'name',
                  value: 'deptId',
                },
                dicUrl: '/api/dept/tree',
                dicMethod: 'post',
                dicQuery: {},
                search: true,
                rules: [{ required: true, message: '请选择责任部门' }],
                addDisabled: false,
                span: 12,
                align: 'left',
                overHidden: true,
              },
              {
                label: '责任人',
                prop: 'responsibleUserId',
                type: 'select',
                span: 12,
                rules: [{ required: true, message: '请选择责任人' }],
                dicUrl: '/api/user/userGrid/1/999',
                props: {
                  label: 'nickName',
                  value: 'userId',
                },
                dicMethod: 'post',
                dicFormatter: (res) => res.listObject,
              },
              {
                label: '通知设置',
                prop: 'noticeSetting',
                span: 12,
                type: 'checkbox',
                dicData: [
                  { value: 'station', label: '站内' },
                  { value: 'email', label: '邮件' },
                ],
              },
              {
                label: '生成任务待办',
                prop: 'autoTaskFlag',
                span: 12,
                labelWidth: 118,
                type: 'switch',
                dicData: [{ value: '0' }, { value: '1' }],
                value: '0',
              },
            ],
          },
          {
            label: '目标数据设置',
            arrow: true,
            prop: 'tjsj',
            column: [
              {
                label: '数据关联',
                prop: 'currentValueType',
                span: 12,
                type: 'radio',
                dicData: [
                  { label: '关联指标', value: '0' },
                  { label: '手动添加', value: '1' },
                ],
                control: (val) => {
                  this.$set(this.defaults.matrixId, 'display', val === '0')
                  this.$set(this.defaults.valueFormat, 'display', val !== '0')
                  this.$set(this.defaults.valueDesc, 'display', val !== '0')
                  this.$set(this.defaults.currentValue, 'disabled', val === '0')
                },
                value: '0',
                // rules: [{ required: true, message: '请输入指标名称' }],
              },
              {
                label: '指标名称',
                prop: 'matrixId',
                type: 'select',
                span: 12,
                rules: [{ required: true, message: '请选择指标' }],
                dicUrl: '/jtx/index/chartList',
                props: {
                  label: 'name',
                  value: 'matrixId',
                },
                dicMethod: 'post',
                filterable: true,
                dicFormatter: (res) => {
                  this.listObj = res.map((item) => ({ ...item }))
                  let item = this.listObj.find((el) => el.matrixId === this.form.matrixId)
                  if (item) {
                    this.form.matrixName = item.name
                    getDBLastData({ panelId: item.sceneId }).then((res) => {
                      let value = res.data?.data?.value || 0
                      this.form.currentValue = value
                    })
                  }
                  return res
                },
                control: async (val) => {
                  let item = this.listObj.find((el) => el.matrixId === val)
                  if (item) {
                    this.form.matrixName = item.name
                    getDBLastData({ panelId: item.sceneId }).then((res) => {
                      let value = res.data?.data?.value || 0
                      this.form.currentValue = value
                    })
                  }
                },
                dicQuery: {
                  publishStatus: '1',
                },
              },
              {
                label: '当前值',
                // labelWidth: 0,
                prop: 'currentValue',
                type: 'number',
                span: 12,
                rules: [{ required: true, validator: validateNum1, trigger: 'blur' }],
              },
              {
                label: '初始值',
                prop: 'initValue',
                type: 'number',
                span: 6,
                min: 0,
                // display: false,
                rules: [{ required: true, trigger: 'blur', message: '请输入初始值' }],
              },
              {
                label: '目标值',
                prop: 'targetValue',
                type: 'number',
                span: 6,
                min: 0,
                // display: false,
                rules: [{ required: true, message: '请输入目标值', validator: validateNum }],
              },
              {
                label: '格式',
                prop: 'valueFormat',
                span: 12,
                // display: false,
              },
              {
                label: '描述',
                prop: 'valueDesc',
                span: 12,
                type: 'textarea',
                // display: false,
              },
            ],
          },
          {
            label: '规则状态',
            arrow: true,
            prop: 'mbzt',
            column: [
              {
                label: '设置类型',
                prop: 'ruleType',
                type: 'radio',
                span: 12,
                dicData: [
                  { label: '手动设置', value: '1' },
                  { label: '设置规则', value: '0' },
                ],
                value: '1',
                control: (val) => {
                  if (val === '0') {
                    this.defaults.targetStatus.display = false
                    this.defaults.ruleJson.display = true
                  } else {
                    this.defaults.targetStatus.display = true
                    this.defaults.ruleJson.display = false
                  }
                },
              },
              {
                label: '设置状态',
                prop: 'targetStatus',
                type: 'select',
                span: 12,
                dicData: [
                  { label: '正常', value: '正常' },
                  { label: '有风险', value: '有风险' },
                  { label: '未完成', value: '未完成' },
                  { label: '完成', value: '完成' },
                ],
                display: true,
              },
              {
                label: '设置规则',
                prop: 'ruleJson',
                display: false,
                span: 24,
              },
            ],
          },
        ],
      },
      isEdit: false,
      dateTypeMap: {
        年度: 'year',
        季度: 'select',
        月: 'month',
        周: 'week',
        日: 'date',
        自定义: 'daterange',
      },
      parentData: {},
    }
  },
  computed: {
    ...mapGetters(['name']),
    targetType() {
      return this.$route.path === '/aim/group-aim-list' ? '0' : '1'
    },
  },
  mounted() {
    this.init()
    // this.getData()
  },
  methods: {
    async submit(_, done) {
      let submitForm = {}
      if (this.$refs.ruleform) {
        let ruleForm = await this.$refs.ruleform?.submit()
        if (!ruleForm) {
          done()
          return
        }
        submitForm = { ...this.form, ruleJson: JSON.stringify(ruleForm), targetType: this.targetType }
      } else {
        submitForm = { ...this.form, targetType: this.targetType }
      }
      if (submitForm.currentValueType === '0') {
        submitForm.valueDesc = ''
        submitForm.valueFormat = ''
      } else {
        submitForm.matrixId = ''
      }
      if (submitForm.ruleType === '0') {
        submitForm.targetStatus = ''
      } else {
        submitForm.ruleJson = ''
      }
      if (submitForm.noticeSetting) submitForm.noticeSetting = submitForm.noticeSetting.join(',')
      if (this.parentId) submitForm['parentId'] = this.parentId
      else submitForm['parentId'] = submitForm.parentId || '0'
      delete submitForm.createdAt
      delete submitForm.updatedAt
      let fn = save
      if (this.id) {
        fn = update
      }
      let { success, message } = await fn(submitForm)
      if (success) {
        this.$message.success(this.id ? '修改成功' : '创建成功')
        this.$emit('close')
        this.$emit('refresh')
      } else {
        this.$message.error(message)
      }
      done()
    },
    async init() {
      if (this.id) {
        getDetail({ id: this.id }).then((res) => {
          let data = res.data
          data = { ...data, noticeSetting: data.noticeSetting ? data.noticeSetting.split(',') : [] }
          // this.form = data
          this.$set(this, 'form', data)
          this.$nextTick(() => {
            if (data.dateType === '自定义') {
              this.$set(this.form, 'datePeriod', [data.beginTargetPeriod, data.endTargetPeriod])
            } else if (data.dateType === '周') {
              this.$set(this.form, 'datePeriod', moment(data.beginTargetPeriod))
            } else if (data.dateType === '季度') {
              let quarter = moment(data.beginTargetPeriod).quarter()
              this.$set(this.form, 'datePeriod', 'Q' + quarter)
            } else {
              this.$set(this.form, 'datePeriod', data.beginTargetPeriod)
            }
            this.$set(this.option, 'detail', this.isDetail)
            if (this.isDetail) {
              let matrixId = this.option.group[1].column[1]
              let valueFormat = this.option.group[1].column[5]
              let valueDesc = this.option.group[1].column[6]
              this.$set(matrixId, 'display', data.currentValueType === '0')
              this.$set(valueFormat, 'display', data.currentValueType === '1')
              this.$set(valueDesc, 'display', data.currentValueType === '1')
              let ruleJson = this.option.group[2].column[2]
              let targetStatus = this.option.group[2].column[1]
              this.$set(ruleJson, 'display', data.ruleType === '0')
              this.$set(targetStatus, 'display', data.ruleType === '1')
            }
          })
        })
      }
      if (this.parentId) {
        getDetail({ id: this.parentId }).then((res) => {
          if (!res.data) return
          this.parentData = res.data
          this.$set(this.parentData, 'datePeriod', [res.data.beginTargetPeriod, res.data.endTargetPeriod])
          this.option.group[0].column.unshift({
            label: '',
            labelWidth: 0,
            prop: 'parent',
            span: 24,
          })
        })
      }
    },
    back() {
      this.$emit('close')
    },
  },
}
</script>

<style lang="scss" scoped>
@import './style/index.scss';

.chart-form-detail {
  background: #fff;
}

.parent-title {
  .el-form-item--small.el-form-item {
    margin: 0 !important;
  }
}

.target {
  .el-form-item--small.el-form-item {
    margin-left: 0 !important;
  }
}

.date {
  .el-form-item--small.el-form-item {
    margin-right: 0 !important;
  }
}

::v-deep {
  .avue-form__menu--right {
    position: sticky;
    bottom: 0;
  }

  .el-drawer .avue-form {
    padding: 20px 20px 0;
  }

  .el-button--small {
    width: 80px;
    height: 32px;
  }

  .el-button.is-circle {
    width: auto;
  }
}
</style>
